package com.slliver.nacosconfig;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;


@EnableDiscoveryClient
@SpringBootApplication
public class NacosConfigApplication {

    public static void main(String[] args) throws InterruptedException {
         SpringApplication.run(NacosConfigApplication.class, args);
    }

    // 1、项目启动的时候就监听配置文件的变化
    // 2、发生变化后拿到最新变化的值
    // 3、发送邮件通知
    /**
    ApplicationRunner applicationRunner(){
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {

            }
        };
    }
    **/
    // 简化上面的写法
    /**
    ApplicationRunner applicationRunner(){
        return (ApplicationArguments args) ->{

        };
    }
    **/
    // 简化上面的写法
    @Bean
    ApplicationRunner applicationRunner(NacosConfigManager nacosConfigManager){
        return args -> {
            System.out.println("项目已经成功移动，开始监听..");
            ConfigService configService = nacosConfigManager.getConfigService();
            configService.addListener("nacos-config-example.properties", "DEFAULT_GROUP", new Listener() {

                @Override
                public Executor getExecutor() {
                    return Executors.newFixedThreadPool(4);
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("开始监听变化的值.." + configInfo);
                    System.out.println("进行邮件通知..");
                }
            });
        };
    }
}
